<template>
  <view class="image-uploader">
    <view class="upload-btn" @click="handleUpload">
      <image src="/static/images/camera.png" mode="aspectFill"></image>
      <text class="upload-text">点击上传</text>
    </view>

    <view
      class="photo-preview"
      v-for="(img, index) in imageList"
      :key="index"
    >
      <image :src="img" mode="aspectFill"></image>
      <view class="delete-photo" @click.stop="removeImage(index)">
        <roc-icon-plus
          type="fas"
          name="times"
          :size="18"
          color="#fff"
        ></roc-icon-plus>
      </view>
    </view>
  </view>
</template>

<script>
import { file } from '@/utils/api/index.js';

export default {
  name: 'ImageUploader',
  props: {
    // 图片列表
    images: {
      type: Array,
      default: () => []
    },
    // 最大上传数量
    maxCount: {
      type: Number,
      default: 9
    }
  },
  data() {
    return {
      imageList: []
    }
  },
  watch: {
    images: {
      handler(newValue) {
        this.imageList = [...(newValue || [])];
      },
      immediate: true
    }
  },
  methods: {
    handleUpload() {
      // 检查是否达到最大上传数量
      if (this.imageList.length >= this.maxCount) {
        uni.showToast({
          title: `最多上传${this.maxCount}张图片`,
          icon: 'none'
        });
        return;
      }
      
      uni.chooseImage({
        count: this.maxCount - this.imageList.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadImages(res.tempFilePaths);
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
        }
      });
    },
    
    // 上传图片到服务器
    async uploadImages(tempFilePaths) {
      uni.showLoading({
        title: '上传中...'
      });
      
      try {
        const uploadPromises = tempFilePaths.map(filePath => file.uploadFile(filePath));
        const results = await Promise.all(uploadPromises);
        
        // 将上传成功的图片URL添加到列表中
        this.imageList = [...this.imageList, ...results];
        
        // 通知父组件图片列表已更新
        this.$emit('update:images', this.imageList);
        
        uni.hideLoading();
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '上传失败: ' + error,
          icon: 'none'
        });
        console.error('上传图片失败:', error);
      }
    },
    
    removeImage(index) {
      this.imageList.splice(index, 1);
      // 通知父组件图片列表已更新
      this.$emit('update:images', this.imageList);
    },
    
    // 获取当前图片列表，供父组件通过ref调用
    getImageList() {
      return this.imageList;
    }
  }
}
</script>

<style lang="scss">
.image-uploader {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
  
  .upload-btn {
    width: 160rpx;
    height: 160rpx;
    margin: 10rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    border: 1px dashed #ccc;
    image{
      width: 48rpx;
      height: 40rpx;
    }
    .upload-text {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
    }
  }
  
  .photo-preview {
    width: 160rpx;
    height: 160rpx;
    margin: 10rpx;
    position: relative;
    border-radius: 8rpx;
    overflow: hidden;
    
    image {
      width: 100%;
      height: 100%;
    }
    
    .delete-photo {
      position: absolute;
      top: 0;
      right: 0;
      width: 40rpx;
      height: 40rpx;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom-left-radius: 8rpx;
    }
  }
}
</style> 